package filemanager;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;

import core.Server;

public class FileTransferServerSocket extends Thread {

	protected static FileTransferServerSocket FILETRANSFERSERVERSOCKET;
	
	ServerSocket server;
	
	HashMap<String, ConnectedFileTransferSocket> users;
	
	public FileTransferServerSocket() {
		
		this.users = new HashMap<String, ConnectedFileTransferSocket>();
		
		try {
			this.server = new ServerSocket(Integer.parseInt(Server.getInstance().getConfigs().get(4)));
			this.start();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void run() {

		Socket user;
		while(!this.server.isClosed())
		{
			try {
				user = this.server.accept();
				new ConnectedFileTransferSocket(user);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}	
	}
	
	public HashMap<String, ConnectedFileTransferSocket> getUsers() {
		return users;
	}

	public void close() throws IOException
	{
		for (Iterator iterator = this.users.values().iterator(); iterator.hasNext();) {
			ConnectedFileTransferSocket fileTransferSocket = (ConnectedFileTransferSocket) iterator.next();
			fileTransferSocket.close();
		}
		
		this.server.close();
	}
	
	public static FileTransferServerSocket getInstance()
	{
		if(FILETRANSFERSERVERSOCKET == null) FILETRANSFERSERVERSOCKET = new FileTransferServerSocket();
		return FILETRANSFERSERVERSOCKET;
	}
	
}